package com.jianggy.jar;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 *动态加载jar包并使用
 *@author jianggy
 *@date 2023/3/1
 *@version 1.0
 **/
public class JarTest {
    public static void main(String[] args) throws Exception {
        Resource resource = new FileSystemResource("C:\\Users\\admin\\Desktop\\test-0.0.1-SNAPSHOT.jar");
        URLClassLoader classLoader = new URLClassLoader(new URL[]{resource.getURL()});
        System.out.println("父类加载器 "+classLoader.getParent());
        System.out.println("资源URL "+resource.getURL()+",资源URI"+resource.getURL().toString());
        Class<?> aClass = classLoader.loadClass("com.jianggy.Calculator");
        Object obj = aClass.newInstance();
        Field field = aClass.getDeclaredField("testField");
        System.out.println(field.getInt(obj));
        Method add = aClass.getMethod("add", float.class,float.class);
        add.invoke(obj, 1,2);
        Method multi = aClass.getMethod("multi", float.class,float.class);
        multi.invoke(obj,4, 8);
    }
}
